import requests

# 音频直链（从问题中复制）
audio_url = "https://audiopay.cos.tx.xmcdn.com/download/1.0.0/storages/4479-audiopay/F6/30/GKwRINsLAnCKABaS9gMrcqDv.m4a?sign=753eb78b4754cbc959a6cf5d3d9ad221&buy_key=FM&timestamp=1748359381761000&token=7679&duration=242"

# 保存路径（可自定义）
save_path = "003_万物有灵.m4a"

# 模拟浏览器请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Referer": "https://www.ximalaya.com/sound/772125003"
}

try:
    # 发起带流式传输的请求
    response = requests.get(audio_url, headers=headers, stream=True)
    response.raise_for_status()  # 自动处理HTTP错误

    # 写入文件
    with open(save_path, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            if chunk:
                f.write(chunk)
    print(f"音频已保存至：{save_path}")

except requests.exceptions.RequestException as e:
    print(f"下载失败，错误信息：{str(e)}")
    print("可能原因：链接已过期/无权限/网络问题")